package com.jack.cms.oss.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.jack.cms.common.constant.tips.Tip;
import com.jack.cms.core.support.HttpKit;
import com.jack.cms.oss.service.FileService;
import com.jack.cms.oss.service.ImageService;

@Controller
@RequestMapping("/upload")
public class OssController {
	private static Logger logger = LoggerFactory.getLogger(OssController.class);
	
	@Autowired
	private ImageService imageService;
	@Autowired
	private FileService fileService;

    /**
     * 上传图片
     */
    @RequestMapping(method = RequestMethod.POST, path = "/image")
    @ResponseBody
    public Tip image(@RequestPart("file") MultipartFile image) {
        try {
			if (image.getBytes() != null && image.getBytes().length > 1024 * 1024) {
				throw new RuntimeException("图片上传大小控制在1M以内，请重新上传");
			}
			String ossFileName = imageService.save(image);
			String url = imageService.getUrl(ossFileName);
			return HttpKit.success(url);
        } catch (Exception e) {
        	logger.error("", e);
			return HttpKit.failed(e.getMessage());
        }
    }
    /**
     * 上传文件
     */
    @RequestMapping(method = RequestMethod.POST, path = "/file")
    @ResponseBody
    public Tip file(@RequestPart("file") MultipartFile file) {
    	try {
    		if (file.getBytes() != null && file.getBytes().length > 1024 * 1024*20) {
    			throw new RuntimeException("图片上传大小控制在20M以内，请重新上传");
    		}
    		String ossFileName = fileService.save(file);
    		String url = fileService.getUrl(ossFileName);
    		return HttpKit.success(url);
    	} catch (Exception e) {
    		logger.error("", e);
    		return HttpKit.failed(e.getMessage());
    	}
    }
}
